<?php
namespace app\Admin\controller;
use app\admin\controller\Base;
use app\admin\model\Link as LinkModel;
class Link extends Base
{
    public function lst()
    {
        $link = new LinkModel();
        if(request()->isPost()){
            $sorts = input('post.');
            foreach ($sorts as $k => $v) {
                $link->update(['id'=>$k,'sort'=>$v]);
            }
            $this->success('更新排序成功！',url('lst'));
            return;
        }
        $links = $link->order('sort asc')->paginate(5);
        $this->assign('links',$links);
        return view();
    }
    public function add()
    {
        if(request()->isPost()){
            $data = [
                'title'=>input('title'),
                'url'=>input('url'),
                'desc'=>input('desc'),
            ];
            $validate = \think\Loader::validate('Link');
            if(!$validate->scene('add')->check($data)){
                $this->error($validate->getError());
                die;
            }
            if(db('Link')->insert($data)){
                $this->success('添加链接成功','lst');
            }else{
                $this->error('添加链接失败');
            }
            return;
        }
        return view();
    }

    public function edit(){
        $id = input('id');
        $link = new LinkModel();
        $list = $link->find($id);
        if (request()->isPost()){
            $data = [
                'id'=>$id,
                'title'=>input('title'),
                'url'=>input('url'),
                'desc'=>input('desc'),
            ];
            $validate = \think\Loader::validate('Link');
            if(!$validate->scene('edit')->check($data)){
                $this->error($validate->getError());
                die;
            }
            $save = $link->update($data);
            if($save !== false){
                $this->success('修改链接成功','lst');
            }else{
                $this->error('修改链接失败');
            }
            return;
        }
        $this->assign('list', $list);
        return view();
    }

    public function del(){
        $id = input('id');
        if(db('Link')->delete($id)){
            $this->success("删除链接成功！", 'lst');
        }else{
            $this->error('删除链接失败');
        }
    }
}
